﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using VNPT.Utility;
using System.IO;
using VNPT.Data;

namespace VNPT.DoiSoat
{
    public partial class uLocRoute : Core.uBase
    {
        //0: tên bản cần chèn, 1 bảng dữ liệu gốc, 2 tháng ,3 danh sách Route VTN hoặc DNK
        string sqlDNK_out = @"INSERT INTO {0} (SO_CG, SO_BG, NGAY, GIOBD, GIOKT,TGLL, INC_ROUTE, OUT_ROUTE)
                              SELECT CHUGOI as SO_CG, BIGOI as SO_BG, NGAYBD as NGAY, GIOBD,
                              STRTRAN(TRANSFORM(HOUR(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(MINUTE(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(sec(CTOT(Giobd) + Tggoi), '##'), ' ', '0') AS GIOKT,
                              TGGOI as TGLL, ALLTRIM(INC_ROUTE) as INC_ROUTE, ALLTRIM(OUT_ROUTE) as OUT_ROUTE
                              FROM '{1}'  Where Month(NGAYBD)={2} and (SUBSTR(ALLTRIM(OUT_ROUTE ),1,4)  IN ({3}));";

        string sqlDNK_inc = @"INSERT INTO {0} (SO_CG, SO_BG, NGAY, GIOBD, GIOKT,TGLL, INC_ROUTE, OUT_ROUTE)
                             SELECT CHUGOI as SO_CG, BIGOI as SO_BG, NGAYBD as NGAY, GIOBD,
                            STRTRAN(TRANSFORM(HOUR(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(MINUTE(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(sec(CTOT(Giobd) + Tggoi), '##'), ' ', '0') AS GIOKT,
                            TGGOI as TGLL, ALLTRIM(INC_ROUTE) as INC_ROUTE, ALLTRIM(OUT_ROUTE) as OUT_ROUTE
                             FROM '{1}' Where Month(NGAYBD)={2} and (SUBSTR(ALLTRIM(INC_ROUTE ),1,4)  IN ({3}));";

        string sqlVTN_out = @"INSERT INTO {0} (SO_CG, SO_BG, NGAY, GIOBD, GIOKT,TGLL, INC_ROUTE, OUT_ROUTE)
                            SELECT CHUGOI as SO_CG, BIGOI as SO_BG, NGAYBD as NGAY, GIOBD,
                            STRTRAN(TRANSFORM(HOUR(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(MINUTE(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(sec(CTOT(Giobd) + Tggoi), '##'), ' ', '0') AS GIOKT,
                            TGGOI as TGLL, ALLTRIM(INC_ROUTE) as INC_ROUTE, ALLTRIM(OUT_ROUTE) as OUT_ROUTE
                            FROM '{1}' Where Month(NGAYBD)={2} and (SUBSTR(ALLTRIM(OUT_ROUTE ),1,4) IN ({3}));";

        string sqlVTN_inc = @"INSERT INTO {0} (SO_CG, SO_BG, NGAY, GIOBD, GIOKT,TGLL, INC_ROUTE, OUT_ROUTE)
                            SELECT CHUGOI as SO_CG, BIGOI as SO_BG, NGAYBD as NGAY, GIOBD, 
                            STRTRAN(TRANSFORM(HOUR(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(MINUTE(CTOT(Giobd) + Tggoi), '##') + ':' + TRANSFORM(sec(CTOT(Giobd) + Tggoi), '##'), ' ', '0') AS GIOKT,
                            TGGOI as TGLL, ALLTRIM(INC_ROUTE) as INC_ROUTE, ALLTRIM(OUT_ROUTE) as OUT_ROUTE
                            FROM '{1}' Where Month(NGAYBD)={2} and (SUBSTR(ALLTRIM(INC_ROUTE ),1,4) IN ({3}));";

        string sqlCreate = @"Create table {0}(
                            SO_CG     Character(16)   NOT NULL,
                            SO_BG     Character (22)  NOT  NULL,
                            NGAY      Date   (8)  NOT  NULL,
                            GIOBD     Character (10)  NOT  NULL,
                            GIOKT     Character  (8)  NOT  NULL,
                            TGLL      Numeric   (10)  NOT  NULL,
                            INC_ROUTE Character (10)  NOT  NULL,
                            OUT_ROUTE Character (10)  NOT  NULL)";

        List<string> li_VTN = new List<string>();
        List<string> li_DNK = new List<string>();
        string NhatKy = "";
        string cnstr = string.Format(@"Provider=vfpoledb;Data Source={0};",DoiSoatSetting.Folder_LUU);
        string txtHienThi = "";


        public uLocRoute()
        {
            InitializeComponent();
            hpRouteList.Click += (a, e) => new fRouteList().ShowDialog();
        }


        public override void LoadSetting()
        {
            Load();
            base.LoadSetting();
        }
        public void Load()
        {
            this.btnThuMucBMT.EditValue = DoiSoatSetting.Folder_BMT;
            this.btnThuMucLuu.EditValue = DoiSoatSetting.Folder_LUU;
            this.btnThuMucTanLoi.EditValue = DoiSoatSetting.Folder_TANLOI;
        }

        public override void SaveSetting()
        {
            DoiSoatSetting.Folder_BMT = this.btnThuMucBMT.Path;
            DoiSoatSetting.Folder_LUU = this.btnThuMucLuu.Path;
            DoiSoatSetting.Folder_TANLOI = this.btnThuMucTanLoi.Path;
            base.SaveSetting();
        }

        private bool CreateTable(string TableName)
        {
            try
            {
                using (DbNetData Db = new DbNetData(cnstr))
                {
                    Db.Open();
                    QueryCommandConfig Query = new QueryCommandConfig(string.Format(sqlCreate, TableName));
                    Db.ExecuteNonQuery(Query);
                }
            }
            catch (Exception ex)
            {
                NhatKy += ex.Message;
                return false;
            }
            return true;
        }

        private void ThucHien()
        {
            var tblDNK_Out = string.Format("CT_DNK_{1}{0:D2}_OUT_DLK01", DoiSoatSetting.THANG, DoiSoatSetting.NAM.ToString().Right(2));
            var tblDNK_Inc = string.Format("CT_DNK_{1}{0:D2}_INC_DLK01", DoiSoatSetting.THANG, DoiSoatSetting.NAM.ToString().Right(2));

            var tblVTN_Out = string.Format("CT_VTN_{1}{0:D2}_OUT_DLK01", DoiSoatSetting.THANG, DoiSoatSetting.NAM.ToString().Right(2));
            var tblVTN_Inc = string.Format("CT_VTN_{1}{0:D2}_INC_DLK01", DoiSoatSetting.THANG, DoiSoatSetting.NAM.ToString().Right(2));

            VNPT.Utility.Profile.Xml xml = new Utility.Profile.Xml();
            var VTN_Route =TachChuoi_Route(DoiSoatSetting.VTN_Route);
            var DNK_Route = TachChuoi_Route(DoiSoatSetting.DNK_Route);


            if (DNK_In.Checked)
            {
                if (CreateTable(tblDNK_Inc))
                    Loc_Route(sqlDNK_inc, tblDNK_Inc, DNK_Route);
                else
                {
                    NhatKy += string.Format("Không tạo được Table {0}!", tblDNK_Inc);
                }
            }

            if (DNK_Out.Checked)
            {
                if (CreateTable(tblDNK_Out))
                    Loc_Route(sqlDNK_out, tblDNK_Out, DNK_Route);
                else
                {
                    NhatKy += string.Format("Không tạo được Table {0}!", tblDNK_Out);
                }
            }
            if (VTN_Out.Checked)
            {
                if (CreateTable(tblVTN_Out))
                    Loc_Route(sqlVTN_out, tblVTN_Out, VTN_Route);
                else
                {
                    NhatKy += string.Format("Không tạo được Table {0}!", tblVTN_Out);
                }
            }
            if (VTN_In.Checked)
            {
                if (CreateTable(tblVTN_Inc))
                    Loc_Route(sqlVTN_inc, tblVTN_Inc, VTN_Route);
                else
                {
                    NhatKy += string.Format("Không tạo được Table {0}!", tblVTN_Inc);
                }
            }

            //if (cXemDL.Checked)
            //{

            //    txtHienThi = string.Format("Đang lấy dữ liệu {0}", tblDNK_Out);
            //    bgWork.ReportProgress(20);
            //    myGridDNK_Inc.Invoke(new Action(() => { myGridDNK_Inc.DataSource = GetData(tblDNK_Out); }));


            //    txtHienThi = string.Format("Đang lấy dữ liệu {0}", tblDNK_Inc);
            //    bgWork.ReportProgress(45);
            //    myGridDNK_Out.Invoke(new Action(() => { myGridDNK_Out.DataSource = GetData(tblDNK_Inc); }));

            //    txtHienThi = string.Format("Đang lấy dữ liệu {0}", tblVTN_Out);
            //    bgWork.ReportProgress(70);
            //    myGridControlVTN_Out.Invoke(new Action(() => { myGridControlVTN_Out.DataSource = GetData(tblVTN_Out); }));

            //    txtHienThi = string.Format("Đang lấy dữ liệu {0}", tblVTN_Inc);
            //    bgWork.ReportProgress(95);
            //    myGridControlVTN_Inc.Invoke(new Action(() => { myGridControlVTN_Inc.DataSource = GetData(tblVTN_Inc); }));

            //    bgWork.ReportProgress(100);
            //}
        }

        private Object GetData(string TableName)
        {
            using (DbNetData Db = new DbNetData(cnstr))
            {
                Db.Open();
                QueryCommandConfig Query = new QueryCommandConfig(string.Format("SELECT TOP 200 * FROM '{0}' ORDER BY NGAY", TableName));
                return Db.GetDataSet(Query).Tables[0];
            }
        }

        private string TachChuoi_Route(string str)
        {
            var t = str.Split(new Char [] {','}, StringSplitOptions.RemoveEmptyEntries);
            string kq = "";
            foreach (var item in t)
            {
                kq += "', '" + item.Trim();
            }
            return kq.Right(kq.Length - 2) + "'";
        }
        
        private void Loc_Route(string strQuery,string TableName, string List)
        {
            //strQuery: 0- tên bản cần chèn, 1 bảng dữ liệu gốc, 2 tháng ,3 danh sách Route VTN hoặc DNK
            using (DbNetData Db = new DbNetData(cnstr))
            {
                Db.Open();
                var files = Directory.GetFiles(DoiSoatSetting.Folder_BMT).Where(p => p.ToUpper().EndsWith(".DBF"));
                var files2 = Directory.GetFiles(DoiSoatSetting.Folder_TANLOI).Where(p => p.ToUpper().EndsWith(".DBF"));
                var fi = files.Union(files2);

                int dem = 0;
                foreach (var item in fi)
                {
                    dem++;
                    if (bgWork.CancellationPending)
                    {
                        continue;
                    }
                    txtHienThi = string.Format("Đang lọc {0} từ {1}...",TableName, item.Right(15));
                    AppendTextBox(txtHienThi);
                    bgWork.ReportProgress((int)(((float)dem/(float)fi.Count())*(float)100));
                    QueryCommandConfig Query = new QueryCommandConfig(string.Format(strQuery, TableName, item, DoiSoatSetting.THANG, List));
                    Db.ExecuteNonQuery(Query);
                }
                txtHienThi = "Hoàn thành...";
            }
        }

        private void bgWork_DoWork(object sender, DoWorkEventArgs e)
        {
            
            ThucHien();
            if (bgWork.CancellationPending)
            {
                e.Cancel = true;
            }
        }

        private void bgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBarControl1.EditValue = e.ProgressPercentage;
            labelControl4.Text = txtHienThi;
        }
        public void AppendTextBox(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
                return;
            }
            memoEdit1.Text = value + Environment.NewLine + memoEdit1.Text;
        }
        private void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           // SauKhiChay();

            progressBarControl1.EditValue = 100;
            labelControl4.Text = "Đã thực hiện xong..."; if (e.Error != null)
            {
                //AppendTextBox(e.Error.Message);
                DevExpress.XtraEditors.XtraMessageBox.Show("Hoàn thành, có phát sinh lỗi.\nVui lòng kiểm tra lại!\n"+e.Error.Message, "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("Đã thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
               // AppendTextBox("Hoàn thành!");
            }
            SauKhiChay();
        }

        

        private void btnKiemTra_Click(object sender, EventArgs e)
        {
            if (!bgWork.IsBusy)
            {
                TruocKhiChay();
                bgWork.RunWorkerAsync();
            }
            else
            {
                string text = "Hệ thống đang lọc dữ liệu, vui lòng kiểm tra lại hoặc dừng trước khi chạy!";
                string caption = "Thông báo!";
                DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        private void TruocKhiChay()
        {
            var m = this.Parent as DevExpress.XtraWizard.WizardPage;
            if (m != null)
            {
                m.AllowNext = false;
                m.AllowBack = false;
            }

            DevExpress.XtraEditors.XtraForm f = null;
            if ((this.Parent as DevExpress.XtraEditors.XtraForm) != null)
            {
                f = this.Parent as DevExpress.XtraEditors.XtraForm;
            }
            else
            {
                if ((this.Parent.Parent as DevExpress.XtraEditors.XtraForm) != null)
                {
                    f = this.Parent.Parent as DevExpress.XtraEditors.XtraForm;
                }
                else
                {
                    if ((this.Parent.Parent.Parent as DevExpress.XtraEditors.XtraForm) != null)
                    {
                        f = this.Parent.Parent.Parent as DevExpress.XtraEditors.XtraForm;
                    }
                }

            }

            if (f != null)
            {
                f.FormClosing += (a1, e1) =>
                {
                    if (bgWork.IsBusy)
                    {
                        string text = "Chương trình đang chạy, không thể đóng form! Vui lòng hủy trước khi đóng chương trình?";
                        string caption = "Xác nhận?";
                        DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        e1.Cancel = true;
                    }
                };

            }
        }


        private void SauKhiChay()
        {
            var m = this.Parent as DevExpress.XtraWizard.WizardPage;
            if (m != null)
            {
                m.AllowNext = true;
                m.AllowBack = true;
            }
        }

        private void btnDung_Click(object sender, EventArgs e)
        {
            string text = "Bạn chắc có muốn dừng thực hiện không?";
            string caption = "Hủy bỏ?";
            if (DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.bgWork.CancelAsync();
            }
        }
    }
}


